<template>
  <el-dialog
    title="入库操作"
    v-model="dialogFormVisible"
    width="60%"
    draggable
    style="position: relative; background-color: #f1f1f1"
    :close-on-click-modal="false"
  >
    <el-form
      ref="ruleFormRef"
      :model="ruleForm"
      :rules="rules"
      label-width="auto"
      class="demo-ruleForm"
      status-icon
      :scroll-to-error="true"
    >
      <el-form-item label="Type" size="normal">
        <el-select v-model="ruleForm.type" placeholder="">
          <el-option
            v-for="item in typeOptions"
            :key="item.value"
            :label="item.label"
            :value="item.value"
          >
          </el-option>
        </el-select>
      </el-form-item>

      <el-form-item label="Model" prop="model_id">
        <el-cascader
          v-if="ruleForm.modelRadio == 1"
          ref="brandCascader"
          v-model="ruleForm.model_id"
          placeholder="Try searchingL Guide"
          :options="brandOptions"
          :props="brandProps"
          :show-all-levels="false"
          filterable
          :before-filter="beforeBrandFilter"
          clearable
          @change="changeModel"
        />

        <el-cascader
          v-if="ruleForm.modelRadio == 2"
          ref="cascder"
          v-model="ruleForm.model_id"
          placeholder="Try searchingL Guide"
          :options="modelOptions"
          :props="modelProps"
          :show-all-levels="false"
          @change="changeModel2"
          filterable
          clearable
        />
        <el-select
          v-if="ruleForm.modelRadio == 3"
          v-model="ruleForm.model_id"
          placeholder="please select"
          :loading="modelLoading"
          :remote-method="remoteMethod"
          @change="changeModel3"
          remote
          filterable
          clearable
        >
          <el-option
            v-for="item in modelList"
            :key="item.id"
            :label="item.model"
            :value="item.id"
          />
        </el-select>

        <el-radio-group v-model="ruleForm.modelRadio" class="ml-4">
          <el-radio label="1" size="large">Brand</el-radio>
          <el-radio label="2" size="large">Classify</el-radio>
          <el-radio label="3" size="large">Search</el-radio>
        </el-radio-group>
      </el-form-item>
      <el-form-item label="Purchaser" prop="purchaser">
        <el-select v-model="ruleForm.purchaser" placeholder="please select">
          <el-option
            v-for="item in purchaserList"
            :key="item.id"
            :label="item.PurchaseName"
            :value="item.id"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="Purchase Price" prop="purchase_price">
        <el-input
          v-model="ruleForm.purchase_price"
          placeholder="please input"
        />
      </el-form-item>
      <el-form-item label="Expected Price" prop="expected_price">
        <el-input
          v-model="ruleForm.expected_price"
          placeholder="please input"
        />
      </el-form-item>
      <el-form-item label="Num" prop="num">
        <el-input v-model.number="ruleForm.num" placeholder="please input" />
      </el-form-item>
      <el-form-item label="remarks">
        <el-input
          v-model="ruleForm.remarks"
          :rows="2"
          type="textarea"
          placeholder="Please input"
        />
      </el-form-item>

      <el-form-item>
        <div class="flex" style="width: 100%; justify-content: center">
          <el-button type="primary" @click="confirm(ruleFormRef)"
            >Confirm</el-button
          >
          <el-button @click="close">Cancel</el-button>
        </div>
      </el-form-item>
    </el-form>
  </el-dialog>
</template>
<script setup lang="ts">
import { ref, reactive, onMounted, nextTick } from "vue";
import { FormInstance, FormRules, ElMessage } from "element-plus";
import * as api from "../../../api2/index";
import { useDemoStore } from "../../../pinia/index";
let token = useDemoStore().token; //token
const dialogFormVisible = ref(false); //弹窗开关

//表单部分
const ruleFormRef = ref<FormInstance>();
const ruleForm = reactive({
  //表单内容
  type: "in",
  model_id: "",
  model_name: "",
  modelRadio: "1",
  purchaser: "",
  purchase_price: "",
  expected_price: "",
  num: "",
  remarks: "",
});
//类别
const typeOptions = ref([
  { value: "in", label: "入库" },
  { value: "broken", label: "破损" },
  { value: "freesample", label: "免费样品" },
]);

//型号
//根据品牌去搜索产品
const brandOptions = ref([]); //品牌列表
const brandLazyLoad = (node, resolve) => {
  if (brandOptions.value.length == 0) {
    return resolve();
  }
  const { data } = node;
  api
    .$getBrandProduct({
      token: token,
      pageNo: 1,
      pageSize: 30,
      brand_id: data.brand_id,
    })
    .then((res) => {
      res.data.data.forEach((item) => {
        item.name = item.model;
      });
      resolve(res.data.data);
    });
};
const brandProps = {
  //品牌props
  value: "product_id",
  label: "name",
  children: "child",
  lazy: true,
  leaf: "product_id",
  emitPath: false,
  lazyLoad: brandLazyLoad,
};
const getBrand = (brand_name) => {
  api
    .$getBrand({
      token,
      pageNo: 1,
      pageSize: 20,
      brand_name,
    })
    .then((res) => {
      brandOptions.value = res.data.data;
    });
};
const beforeBrandFilter = (value) => {
  //替代搜索逻辑
  getBrand(value);
  return false;
};
const brandCascader = ref();
const changeModel = (val) => {
  let node = brandCascader.value.getCheckedNodes();
  ruleForm.model_name = node[0].label;
};

//根据型号分类选择产品
const modelOptions = ref([]); //型号分类列表
const lazyLoad = (node, resolve) => {
  //型号分类动态加载函数
  if (modelOptions.value.length == 0) {
    return resolve();
  }
  const { data } = node;
  api
    .getCategoryProduct({
      token: token,
      category_id: data.category_id,
    })
    .then((res) => {
      res.data.data.forEach((item) => {
        item.category_id = item.product_id;
      });
      resolve(res.data.data);
    });
};
const modelProps = {
  //型号分类props
  value: "category_id",
  label: "name",
  children: "child",
  lazy: true,
  leaf: "product_id",
  emitPath: false,
  lazyLoad: lazyLoad,
};
const getProductClassify = () => {
  //获取型号分类
  api
    .getProductClassify({
      token: token,
    })
    .then((res) => {
      let option = [
        {
          name: "B2C",
          category_id: "-1",
          child: res.data.B2C,
        },
        {
          name: "AllProduct",
          category_id: "-2",
          child: res.data.AllProduct,
        },
      ];
      modelOptions.value = option;
    });
};
const cascder = ref();
const changeModel2 = (val) => {
  let node = cascder.value.getCheckedNodes();
  ruleForm.model_name = node[0].label;
};

//根据型号去搜索产品
const modelList = ref([]); //型号搜索列表
const modelLoading = ref(false); //型号搜索加载
const remoteMethod = (query) => {
  //型号搜索函数
  if (query) {
    modelLoading.value = true;
    setTimeout(() => {
      modelLoading.value = false;
      api
        .getModel({
          token: token,
          model: query,
        })
        .then((res) => {
          modelList.value = res.data;
        });
    }, 400);
  } else {
    modelList.value = [];
  }
};
const changeModel3 = (val) => {
  let obj = modelList.value.find((item) => {
    return item.id == val;
  });
  ruleForm.model_name = obj.name;
};

//型号

//采购
const purchaserList = ref([]); //采购列表
const getPurchaseList = () => {
  //获取采购列表
  api
    .getPurchaseList({
      token,
    })
    .then((res) => {
      purchaserList.value = res.data;
    });
};
//采购

//校检规则
const isPrice = (rule, value, callback) => {
  //校检价格
  if (!value) {
    return callback(new Error("Please input the Price"));
  } else if (!Number(value)) {
    return callback(new Error("Please input digits"));
  } else if (value <= 0) {
    return callback(new Error("Please don't be less than zero"));
  } else {
    return callback();
  }
};
const isNum = (rule, value, callback) => {
  //校检数量
  if (!value) {
    return callback(new Error("Please input the Num"));
  } else if (!Number.isInteger(value)) {
    return callback(new Error("Please input digits"));
  } else if (value <= 0) {
    return callback(new Error("Please don't be less than zero"));
  } else {
    return callback();
  }
};
const rules = reactive<FormRules>({
  //校检规则
  model_id: [
    {
      required: true,
      message: "Please select Model",
      trigger: "change",
    },
  ],
  purchaser: [
    {
      required: true,
      message: "Please select Purchaser",
      trigger: "change",
    },
  ],
  purchase_price: [
    {
      validator: isPrice,
      trigger: "blur",
    },
  ],
  expected_price: [
    {
      validator: isPrice,
      trigger: "blur",
    },
  ],
  num: [
    {
      validator: isNum,
      trigger: "blur",
    },
  ],
});
//校检规则

const show = () => {
  //弹窗显示
  getBrand("");
  getPurchaseList();
  getProductClassify();
  dialogFormVisible.value = true;
};
const close = () => {
  //弹窗关闭
  dialogFormVisible.value = false;
};
const confirm = async (formEl) => {
  //表单提交
  if (!formEl) return;
  await formEl.validate((valid, fields) => {
    if (valid) {
      api
        .putInStorage({
          token,
          model: ruleForm.model_name,
          product_id: ruleForm.model_id,
          purchase_id: ruleForm.purchaser,
          purchase_price: ruleForm.purchase_price,
          expected_price: ruleForm.expected_price,
          quantity: ruleForm.num,
          type: "in",
          remarks: ruleForm.remarks,
        })
        .then((res) => {
          ElMessage({
            type: "success",
            message: res.Message,
          });
        });
    } else {
      console.log("error submit!", fields);
    }
  });
};
defineExpose({
  show,
});
onMounted(() => {});
</script>
<style lang="less" scoped></style>
